#include "homepage.h"
#include "ui_homepage.h"
#include "globalval.h"
#include <QDebug>

HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);

    ui->line_ip->setStyleSheet("QLineEdit { background: transparent; background-color: rgba(255, 255, 255, 50); color:white;}");
    ui->listWidget->setStyleSheet("QListWidget { background: transparent; background-color: rgba(255, 255, 255, 50); color:white;}");
    ui->connect_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color: white;}");
    this->setWindowIcon(QIcon(":/image/warehouse.png"));
    this->setWindowTitle("冷链物流管理");

    //实例化四个界面
    m0Wig = new M0Wig;
    modbusWig = new ModbusWig;
    mbappWig = new MbappWig;
    setWig = new SetWig;
    searchWig = new searchwig;

    //将五个界面依次添加到堆栈窗体
    ui->stackedWidget->addWidget(m0Wig);        //监测
    ui->stackedWidget->addWidget(modbusWig);    //控制
    ui->stackedWidget->addWidget(mbappWig);
    ui->stackedWidget->addWidget(setWig);       //视频监控
    ui->stackedWidget->addWidget(searchWig);    //设备搜索


    //连接列表界面和堆栈窗体的信号
    QObject::connect(ui->listWidget, SIGNAL(currentRowChanged(int)),
                     ui->stackedWidget, SLOT(setCurrentIndex(int)));



    //哪个界面需要接收Mqtt的消息，就订阅这个信号，然后在自己的界面文件中处理消息
//    QObject::connect(mqtt, SIGNAL(dataUpSignal(QByteArray)),
//                     modbusWig, SLOT(dataUpSlot(QByteArray)));

    MqttHandler *mqtt = new MqttHandler;
    GlobalVal::mqtt = mqtt;

    QObject::connect(mqtt,&MqttHandler::dataUpSignal,m0Wig,&M0Wig::mqttRecv);


    connect(searchWig,&searchwig::IpSignal,this,&HomePage::handleipsignal);

}

HomePage::~HomePage()
{
    delete ui;
}

void HomePage::on_connect_button_clicked()
{
    //mqtt相关
    QString ip = ui->line_ip->text();


    GlobalVal::mqtt->setHost(QHostAddress(ip));
    GlobalVal::mqtt->setPort(1883);
    GlobalVal::mqtt->connectToHost();

    connect(GlobalVal::mqtt, SIGNAL(connected()), this, SLOT(onMqttConnected()));

    GlobalVal::mqtt->connectToHost();
}

void HomePage::onMqttConnected()
{
    qDebug() << "onMqttConnected() called";
    ui->connect_button->setEnabled(false);
    ui->connect_button->setText("已连接");
    ui->connect_button->setStyleSheet("background-color:WhiteSmoke;");
}



void HomePage::handleipsignal(QString ip)
{
    ui->line_ip->setText(ip);
}



void HomePage::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap background(":/image/bg.png");

    // 自适应窗口大小缩放背景（保持比例）
    QPixmap scaled = background.scaled(this->size(), Qt::KeepAspectRatioByExpanding);
    painter.drawPixmap(0, 0, scaled);

    // 继续默认绘制
    QWidget::paintEvent(event);
}
